package com.zc.servlet;

import java.io.File;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.zc.entity.User;
import com.zc.service.Service;
import com.zc.utils.StringUtils;
import com.zc.utils.servletUtils;

import entity.Hotel;
import entity.Payment;

/**
 * 穷游后台管理
 */
@WebServlet("/Myservlet")
@MultipartConfig
public class MyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private JSONObject json=new JSONObject();
	private Service service=new Service();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.获取前端请求的内容是什么
		String method = request.getParameter("method");
		String methodName = request.getMethod();
		System.out.println("doGet---->"+methodName+" method="+method);
		if(method==null) {
			System.out.println("method==null");
			return;
		}
		if("getCaptcha".equalsIgnoreCase(method)){//获取短信验证码
			getCaptcha(request,response);
		}else if("showImg".equalsIgnoreCase(method)){//获取短信验证码
			showImg(request,response);
		}else if("getEmailCaptcha".equalsIgnoreCase(method)){//获取短信验证码
			getEmailCaptcha(request,response);
		}else if("bind_Email".equalsIgnoreCase(method)){//获取短信验证码
			bind_Email(request,response);
		}else if("unbind_Email".equalsIgnoreCase(method)){//获取短信验证码
			unbind_Email(request,response);
		}else if("unbind_phone".equalsIgnoreCase(method)){//获取短信验证码
			unbind_phone(request,response);
		}else if("bind_phone".equalsIgnoreCase(method)){//获取短信验证码
			bind_phone(request,response);
		}else if("getIndent".equalsIgnoreCase(method)){//获取短信验证码
			getIndent(request,response);
		}else if("deleteIndent".equalsIgnoreCase(method)){//获取短信验证码
			deleteIndent(request,response);
		}else if("exit".equalsIgnoreCase(method)) {
			exit(request,response);
		}else {
			System.out.println("无此method="+method);
		}
	}
	
    private void exit(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	// 清除Session域中的值
		request.getSession().invalidate();
		response.sendRedirect(request.getContextPath()+"/jsp/zc/travel_login.jsp");
	}

	private void deleteIndent(HttpServletRequest request, HttpServletResponse response) {
    	json.clear();
		System.out.println("deleteIndent");
		String number=request.getParameter("number");
		System.out.println("number:"+number);
		int r=service.delete("DELETE FROM payment WHERE number=?",number);
		json.fluentPut("code",r);
		try {
			servletUtils.print(json, response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
     * 获取订单
     * @param request
     * @param response
     */
	private void getIndent(HttpServletRequest request, HttpServletResponse response) {
		json.clear();
		System.out.println("getIndent");
		int user_id = Integer.parseInt(request.getParameter("user_id"));
		System.out.println("获取到的主用户id---->"+user_id);
		List<Payment> payMents=new ArrayList<Payment>();
		List<List<String>> result=new ArrayList<List<String>>(); 
		payMents=service.queryJavaBean(Payment.class,"select * from payment where user_id ="+user_id);
		for(int i=0;i<payMents.size();i++) {
			List<String> re=new ArrayList<String>();
			re.add(payMents.get(i).getNumber());
			re.add(service.queryJavaBean(Hotel.class,"select * from hotel where hotel_id=?",payMents.get(i).getHotel_id()).get(0).getHotel_text());
			Date over=StringUtils.StringToData(payMents.get(i).getCreate_time());
			Date now=Calendar.getInstance().getTime();
			re.add((now.getTime()-over.getTime())/1000+"");
		    re.add(payMents.get(i).getPrice());
		    re.add(payMents.get(i).getStatus());
		    result.add(re);
		}
		json.fluentPut("code",result);
		try {
			servletUtils.print(json, response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.获取前端请求的内容是什么
		String method = request.getParameter("method");
		String methodName = request.getMethod();
		System.out.println("doPost---->"+methodName+" method="+method);
		if(method==null) {
			System.out.println("method==null");
			return;
		}
		if("updateUser".equalsIgnoreCase(method)) {//更新用户名信息
			updateUser(request,response);
		}else if("login".equalsIgnoreCase(method)){//登陆
			login(request,response);
		}else if("checkUser".equalsIgnoreCase(method)){//检查用户名是否重复
			checkUser(request,response);
		}else if("checkPhone".equalsIgnoreCase(method)) {
			checkPhone(request,response);
		}else if("register".equalsIgnoreCase(method)) {
			register(request,response);
		}else if("updateUserName".equalsIgnoreCase(method)) {
			updateUserName(request,response);
		}else if("updateUserPass".equalsIgnoreCase(method)) {
			updateUserPass(request,response);
		}else if("updateUserImg".equalsIgnoreCase(method)){
			updateUserImg(request,response);
		}else {
			System.out.println("无此method="+method);
		}
	}
	private void bind_Email(HttpServletRequest request, HttpServletResponse response) {
		json.clear();
		String email=request.getParameter("email");
		String userName=request.getParameter("userName");
		System.out.println("email="+email);
		System.out.println("userName="+userName);
		int result=service.updateDB("UPDATE  zc_user SET email=? WHERE userName=?",email,userName);
		if(result==1) {
			request.getSession().setAttribute("user",service.queryJavaBean(User.class,"select * from zc_user where userName=?",userName).get(0));
		}
		json.fluentPut("code",result);
		try {
			servletUtils.print(json, response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private void unbind_Email(HttpServletRequest request, HttpServletResponse response) {
		
		json.clear();
		String email=request.getParameter("email");
		System.out.println("email="+email);
		User user=service.queryJavaBean(User.class,"select * from zc_user where email=?",email).get(0);
		int result=service.updateDB("UPDATE  zc_user SET email=? WHERE email=?", null,email);
		user.setEmail(null);
		if(result==1) {
			request.getSession().setAttribute("user",user);
		}
		json.fluentPut("code",result);
		try {
			servletUtils.print(json, response);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}
	private void bind_phone(HttpServletRequest request, HttpServletResponse response) {
		
		json.clear();
		String email=request.getParameter("email");//phone
		String userName=request.getParameter("userName");
		System.out.println("phone="+email);
		System.out.println("userName="+userName);
		User user=service.queryJavaBean(User.class,"select * from zc_user where userName=?",userName).get(0);
		int result=service.updateDB("UPDATE  zc_user SET phone=? WHERE userName=?",email,userName);
		user.setPhone(email);
		if(result==1) {
			request.getSession().setAttribute("user",user);
		}
		json.fluentPut("code",result);
		try {
			servletUtils.print(json, response);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}
	private void unbind_phone(HttpServletRequest request, HttpServletResponse response) {
		
		json.clear();
		String email=request.getParameter("email");
		System.out.println("email="+email);
		User user=service.queryJavaBean(User.class,"select * from zc_user where phone=?",email).get(0);
		int result=service.updateDB("UPDATE  zc_user SET phone=? WHERE phone=?", null,email);
		user.setPhone(null);
		if(result==1) {
			request.getSession().setAttribute("user",user);
		}
		json.fluentPut("code",result);
		
		try {
			servletUtils.print(json, response);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}
	/**
	 * 获取邮箱验证码
	 * @param request
	 * @param response
	 */
	private void getEmailCaptcha(HttpServletRequest request, HttpServletResponse response) {
		
		json.clear();
		String email=request.getParameter("email");
		System.out.println("email="+email);
		String r=service.getMailCaptach(email);
		if(r==null) {//服务异常出问题
			json.fluentPut("code",-1);
		}else {
			//数据库查电话号码,code: -1服务异常出问题，其他：验证码
			json.fluentPut("code",r);
		}
		try {
			servletUtils.print(json, response);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}
	/**
	 * 顯示圖片
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void showImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String path=request.getParameter("imgPath");//圖片路勁 
		File imgFile=new File(path);//圖片文件
		if(imgFile!=null&&imgFile.exists()) {
			byte[] b=new byte[1028];
			int  len=0;
			InputStream in=new FileInputStream(imgFile);
			ServletOutputStream  out=response.getOutputStream();
			while((len=in.read(b))!=-1) {
				out.write(b,0, len);
			}
			out.flush();
			out.close();
			in.close();
			response.flushBuffer();
		}
	}
	/**
	 * 更改用户头像
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void updateUserImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		json.clear();
		List<String> imgPath=null;
		try {
			// 1:获取图片名称的方法
			imgPath = servletUtils.getFile(request);
		} catch (Exception e1) {
			e1.printStackTrace();
			json.fluentPut("code",-2);//获取文件失败
		}
		if(imgPath!=null&&imgPath.size()!=0) {
			System.out.println("图片路径2--->"+imgPath.get(0));
			
			
			String oldName=request.getParameter("oldName");
			System.out.println("newPass="+imgPath.get(0));
			System.out.println("oldName="+oldName);
			int r=service.updateDB("update zc_user set img=? where username=?",imgPath.get(0),oldName);
			if(r==-1) {//数据库异常出问题
				json.fluentPut("code",-1);
			}else {
				//数据库查电话号码,code: -1数据库故障    其他：查询到使用该用户名的数量
				json.fluentPut("code",r);
			}
			User user=service.queryJavaBean(User.class,"select * from zc_user where username=?",oldName).get(0);
			request.getSession().setAttribute("user",user);
		}
		try {
			servletUtils.print(json, response);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}
	/**
	 * 更改密码
	 * @param request
	 * @param response
	 */
	private void updateUserPass(HttpServletRequest request, HttpServletResponse response) {
		
		json.clear();
		String newPass=request.getParameter("newPass");
		String oldPass=request.getParameter("oldPass");
		String oldName=request.getParameter("oldName");
		System.out.println("newPass="+newPass);
		System.out.println("oldPass="+oldPass);
		System.out.println("oldName="+oldName);
		int r=service.updateDB("update zc_user set password=? where username=? and password=?",newPass,oldName,oldPass);
		if(r==-1) {//数据库异常出问题
			json.fluentPut("code",-1);
		}else {
			//数据库查电话号码,code: -1数据库故障    其他：查询到使用该用户名的数量
			json.fluentPut("code",r);
		}
		try {
			servletUtils.print(json, response);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}

	/**
	 *检查用户名是否重复
	 * @param request
	 * @param response
	 */
	private void updateUserName(HttpServletRequest request, HttpServletResponse response) {
		
		json.clear();
		String newName=request.getParameter("newName");
		String oldName=request.getParameter("oldName");
		System.out.println("newName="+newName);
		System.out.println("oldName="+oldName);
		Long r=service.queryNum("select count(*) from zc_user where username=?",newName);
		if(r==null) {//数据库异常出问题
			json.fluentPut("code",-1);
		}else {
			//数据库查电话号码,code: -1数据库故障    其他：查询到使用该用户名的数量
			json.fluentPut("code",r);
		}
		try {
			servletUtils.print(json, response);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}

	/**
	 * 注册
	 * @param request
	 * @param response
	 */
	private void register(HttpServletRequest request, HttpServletResponse response) {
		
		json.clear();
		List<String> params=new ArrayList<String>();
		params.add(request.getParameter("username"));
		params.add(request.getParameter("phone"));
		params.add(request.getParameter("password"));
		params.add("http://localhost:8080/JavaWeb%E9%A1%B9%E7%9B%AE_%E7%AC%AC%E5%85%AD%E7%BB%84/images/zc/person/120.png");
		int r=service.updateDB("INSERT INTO zc_user(userName,phone,PASSWORD,img) VALUE(?,?,?,?)",params.toArray());
		if(r==-1) {//数据库异常出问题
			json.fluentPut("code",-1);
		}else {
			//数据库查电话号码,code: -1数据库故障    其他：查询到使用该用户名的数量
			json.fluentPut("code",r);
		}
		try {
			servletUtils.print(json, response);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}

	/**
	 * 检查手机号是否重复
	 * @param request
	 * @param response
	 */
	private void checkPhone(HttpServletRequest request, HttpServletResponse response) {
		
		json.clear();
		Long r=service.queryNum("select count(*) from zc_user where phone=?",request.getParameter("phone"));
		if(r==null) {//数据库异常出问题
			json.fluentPut("code",-1);
		}else {
			//数据库查电话号码,code: -1数据库故障    其他：查询到使用该用户名的数量
			json.fluentPut("code",r);
		}
		try {
			servletUtils.print(json, response);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}

	/**
	 * 检查用户名是否重复
	 * @param request
	 * @param response
	 */
	private void checkUser(HttpServletRequest request, HttpServletResponse response) {
		
		json.clear();
		Long r=service.queryNum("select count(*) from zc_user where username=?",request.getParameter("username"));
		if(r==null) {//数据库异常出问题
			json.fluentPut("code",-1);
		}else {
			//数据库查电话号码,code: -1数据库故障    其他：查询到使用该用户名的数量
			json.fluentPut("code",r);
		}
		try {
			servletUtils.print(json, response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 登陆
	 * @param request
	 * @param response
	 */
	private void login(HttpServletRequest request, HttpServletResponse response) {
		json.clear();
		String type=request.getParameter("type");
		String name=request.getParameter("name");
		String pass=request.getParameter("pass");
		String account_type=request.getParameter("account_type");
		String sql=null;
		System.out.println("登陆请求：");
		System.out.println("1账号登陆，2短信登陆:"+type);
		System.out.println("账号:"+name);
		System.out.println("密码or验证码:"+pass);
		System.out.println("账号登陆类型：1用户名 2手机号 3邮箱："+account_type);
		List<Object> params=new ArrayList<Object>();
		if("1".equals(type)) {//账号登陆
			if("1".equals(account_type)) {//用户名登陆
				sql="select * from zc_user where userName=? and password=?";
			}else if("2".equals(account_type)) {//手机号
				sql="select * from zc_user where phone=? and password=?";
			}else if("3".equals(account_type)) {//邮箱
				sql="select * from zc_user where email=? and password=?";
			}
			params.add(name);
			params.add(pass);
		}else if("2".equals(type)){//短信登陆
			params.add(name);
			sql="select * from zc_user where phone=?";
		}
		if(sql==null) {
			System.err.println("login函数--登陆类型范围错误（1-2）   error");
			return ;
		}
		List<User> user= service.queryJavaBean(User.class, sql,params.toArray());
		if(user==null) {
			json.fluentPut("code",-1);//code:-1数据库错误，0账号或密码错误 1成功
		}else if(user.size()==0) {
			System.out.println(user.size());
			json.fluentPut("code",0);//code:-1数据库错误，0账号或密码错误 1成功
		}else{//成功
			HttpSession session=request.getSession();
			String str_perfer=user.get(0).getTripprefer();//偏好
			System.out.println("str="+str_perfer);
			Integer perfer[]=new Integer[14];
			for(int i=0;i<perfer.length;i++) {
				perfer[i]=0;
			}
			if(str_perfer!=null) {
				for(int i=0;i<perfer.length;i++) {
					if(str_perfer.indexOf(""+(i+1))!=-1) {
						perfer[i]=1;//选中
					}
				}
			}
			session.setAttribute("user", user.get(0));
			session.setAttribute("user_perfer",perfer);
			json.fluentPut("code",1);//code:-1数据库错误，0账号或密码错误 1成功
		}
		try {
			servletUtils.print(json, response);//发送到前端
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取短信验证码
	 * @param request
	 * @param response
	 */
	private void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
		json.clear();
		System.out.println("获取验证码");
		String phone=request.getParameter("phone");
		System.out.println("phone="+phone);
		String captcha=service.getCaptcha(phone);
		System.out.println("验证码="+captcha);
		if(captcha==null) {//短信服务出问题
			json.fluentPut("code",-1);
		}else {
			//数据库查电话号码,code: -1短信服务故障    其他：成功
			json.fluentPut("code",captcha);
		}
		try {
			servletUtils.print(json, response);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}
	/**
	 * 更新用户个人资料
	 * @param request
	 * @param response
	 */
	private void updateUser(HttpServletRequest request, HttpServletResponse response) {
		try {
			json.clear();
			User user=servletUtils.getFormTable(request, User.class);
			String birth=request.getParameter("birthyear")+"年"+request.getParameter("birthmonth")+"月"+request.getParameter("birthday")+"日";
			user.setBirth(birth);
			String oldName=request.getParameter("oldName");
			System.out.println(user);
			System.out.println("oldName="+oldName);
			List<String> params=new ArrayList<String>();
			params.add(user.getUserName());
			params.add(user.getGender());
			params.add(user.getBirth());
			params.add(user.getNewAddr());
			params.add(user.getOldAddr());
			params.add(user.getBio());
			params.add(user.getSite());
			params.add(user.getTripprefer());
			params.add(oldName);
			//存到数据库
			int r=service.updateDB("UPDATE zc_user SET userName=?,"
													  + "gender=?,"
													  + "birth=?,"
													  + "newAddr=?,"
													  + "oldAddr=?,"
													  + "bio=?,"
													  + "site=?,"
													  + "tripprefer=?"
													  + " WHERE username=?",params.toArray());
			//未完-----------------------------------------------
			json.fluentPut("code",r);//r=1成功，r=0失败，其他：出问题
			if(r==1) {
				User newUser=service.queryJavaBean(User.class,"select * from zc_user where username=?",user.getUserName()).get(0);
				HttpSession session=request.getSession();
				String str_perfer=user.getTripprefer();//偏好
				Integer perfer[]=new Integer[14];
				for(int i=0;i<perfer.length;i++) {
					perfer[i]=0;
				}
				if(str_perfer!=null) {
					for(int i=0;i<perfer.length;i++) {
						if(str_perfer.indexOf((i+1)+"")!=-1) {
							perfer[i]=1;//选中
						}
					}
				}
				session.setAttribute("user",newUser);
				session.setAttribute("user_perfer",perfer);
			}
		} catch (Exception e) {
			
			e.printStackTrace();
			json.fluentPut("code",-1);//数据库故障
		}finally {
			try {
				servletUtils.print(json, response);
			} catch (IOException e) {
				
				e.printStackTrace();
			}
		}
	}

}
